<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
      <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">博客首页</el-breadcrumb-item>
          <el-breadcrumb-item><a href="/">发布文章</a></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-form ref="form" :model="article" label-width="80px">
        <el-form-item label="文章标题">
          <el-input v-model="article.title"></el-input>
        </el-form-item>
        <el-form-item label="文章简介">
          <el-input type="textarea" v-model="article.summary"></el-input>
        </el-form-item>
        <el-form-item  label="文章内容">
          <el-tiptap
            v-model="article.content.content"
            :extensions="extensions"
            height="400"
            placeholder="请输入文章内容"
          ></el-tiptap>
        </el-form-item>
        <el-form-item label="文章封面">
            <!-- 封面裁剪 -->
            <div class="cropper-app">
              <el-upload
                action="#"
                class="btn"
                drag
                :auto-upload="true"
                :show-file-list="false"
                :on-change="handleCrop"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  class="Group-img"
                  v-if="loadingtext"
                  title="点击更换封面"
                  :src="article.articlePic"
                />
                <el-button
                  plain
                  round
                  class="img-btn"
                  v-if="!loadingtext"
                  size="mini"
                  >添加封面</el-button
                >
              </el-upload>

              <!-- 剪裁组件弹窗 -->
              <cropperImage
                :dialogVisible="showCropper"
                :cropper-option="cropperOption"
                :file-size="fileSize"
                :cropper-style="cropperStyle"
                @close="showCropper = false"
                @uploadCropper="uploadImg"
              />
            </div>
        </el-form-item>
        <el-form-item label="文章标签">
          <div>
            <el-radio v-model="article.tag[0].tag" label="生活" border>生活</el-radio>
            <el-radio v-model="article.tag[0].tag" label="心情" border>心情</el-radio>
            <el-radio v-model="article.tag[0].tag" label="学习" border>学习</el-radio>
            <el-radio v-model="article.tag[0].tag" label="总结" border>总结</el-radio>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onPublish">发表</el-button>
          <el-button>取消</el-button>
        </el-form-item>

      </el-form>
    </el-card>

    <!-- 弹出层   -->
    <el-dialog
      title="上传封面"
      :visible.sync="dialogUploadVisible"
      :append-to-body="true"
    >
      <el-upload
        class="upload-demo"
        drag
        action="http://localhost:8080/api/articles/updateCover"
        name="uploadBody.ArticlePic"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import cropperImage from './Copper'
import {getArticleContent,publishArticle,updateCover} from '@/api/articles'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  HorizontalRule,
  Fullscreen,
  Preview,
  CodeBlock,
  TextColor,
  FormatClear,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  History,
  TrailingNode,
  HardBreak,
  LineHeight,
  Indent
} from 'element-tiptap'
import 'element-tiptap/lib/index.css'
export default {
  name: 'publish',
  // 接收父组件传入的参数
  props: {

  },
  // 注册组件
  components: {
    'el-tiptap': ElementTiptap,
    cropperImage
  },
  // 数据
  data () {
    return {
      breaShow: true,
      cropperData: {},
      showCropper: false, // 显示裁剪弹窗
      canCropper: false,
      loadingtext: false,
      fileSize: 2, // 限制文件上传大小
      formate: new FormData(),
      cropperOption: {
        img: '',
        autoCropWidth: 300,
        autoCropHeight: 180
      },
      cropperStyle: {
        width: '600px',
        height: '300px'
      },
      article: {
          title: "",
          summary: "",
          tag: [
          {tag: ""}, 
          {tag: ""}
        ],
        articleId: "", 
        status: 1,
        articlePic: "", 
          content: {
              "content": "",
              "contentHtml": ""
          }
      },
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // render command-button in bubble menu.
        new Underline({ bubble: true, menubar: false }), // render command-button in bubble menu but not in menubar.
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(), // 有序列表
        new TodoItem(),
        new TodoList(),
        new Fullscreen(),
        new Preview(),
        new CodeBlock(),
        new TextColor(),
        new FormatClear(),
        new Table({ resizable: true }),
        new TableHeader(),
        new TableCell(),
        new TableRow(),
        new History(),
        new TrailingNode(),
        new HardBreak(),
        new HorizontalRule(),
        new LineHeight(),
        new Indent()
      ],
      breaShow: true,
      cropperData: {},
      showCropper: false, // 显示裁剪弹窗
      canCropper: false,
      loadingtext: false,
      fileSize: 2, // 限制文件上传大小
      formate: new FormData(),
      cropperOption: {
        img: '',
        autoCropWidth: 300,
        autoCropHeight: 180
      },
      cropperStyle: {
        width: '600px',
        height: '300px'
      },
      dialogVisible: false,
      dialogUploadVisible: false
    }
  },
  // 属性值计算
  computed: {},
  // 数据侦听
  watch: {},
  // vue实例被创建时
  created() {
    this.loadTags()
    // this.updateRequest()
    // console.log(articleId)
    // 由于这里让发布和编辑使用的同一个组件，所以这里要进行判断
    // 如果路由的路径参数有id，那么请求展示文章内容
    if (this.$route.query.id) {
      this.loadArticle()
    }
  },
  // vue实例被挂载至dom上时
  mounted () {},
  // 实例方法
  methods: {
    async  loadTags() {
      const id = {
        "articleId": 36
      }
      const { res: data } = await getArticleContent(id);
    },
    onPublish() {
      publishArticle(this.article).then(res => {
          // console.log(res)
          console.log('发布成功!')
      }) 

    },
    // 修改文章，加载文章内容
    // loadArticle() {
    //   // 找到数据接口。封装请求方法。请求获取数据。模板绑定展示
    //   getArticleContent(this.articleId).then(res => {
    //     console.log(res)
    //   })
    // }
    // updateRequest(file) {
    //   const fd = new FormData()
    //   fd.append('ArticlePic', file)

    //   // const 
    //   updateCover(fd).then(res => {
    //     console.log('res')
    //   })
    // }

    // 点击弹出剪裁框
    handleCrop (file) {
      this.$nextTick(() => {
        if (this.canCropper) {
          this.cropperOption.img = window.URL.createObjectURL(file.raw)
          this.showCropper = this.canCropper
        }
      })
    },
    // 上传前校验
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2 MB!')
      }
      // 校验通过后显示裁剪框
      this.canCropper = isJPG && isLt2M
      return false
    },
    // 自定义的图片提交事件
    uploadImg (f, data) {
      const formdata = new FormData()
      formdata.append('ArticlePic', f)
      this.loadingtext = true
      this.cropperData.iconUrl = data
      this.showCropper = false
      this.formate = formdata
      updateCover(formdata).then(res => {
        this.article.articlePic = res.data.data
        // console.log(res)
      })
    },

  },
  activated () {},
  deactivated () {},
  destroyed () {},
}
</script>
<style lang='less' scoped>
/deep/ .Group-img {
  width: 360px;
  height: 180px;
}
</style>